package org.qpcr.community.device.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.qpcr.community.device.service.CalibrationResponseListenerService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * 响应式服务启动配置
 * 负责管理所有响应式服务的启动顺序和配置
 */
@Component
@Slf4j
@RequiredArgsConstructor
@Order(5) // 在CalibrationCmdService之前启动
public class ReactiveServiceStartupConfig implements CommandLineRunner {

    private final CalibrationResponseListenerService responseListenerService;

    @Override
    public void run(String... args) throws Exception {
        log.info("响应式服务启动配置初始化...");

        // 延迟3秒启动监听服务，确保基础服务已启动
        Mono.delay(Duration.ofSeconds(3))
            .doOnSuccess(tick -> {
                log.info("启动校准响应监听服务...");
                try {
                    responseListenerService.startCalibrationResponseListener();
                    log.info("校准响应监听服务启动成功");
                } catch (Exception e) {
                    log.error("启动校准响应监听服务失败: {}", e.getMessage(), e);
                }
            })
            .doOnError(error -> {
                log.error("启动响应式服务时发生错误: {}", error.getMessage(), error);
            })
            .subscribe();
    }
}
